
import os
import wx.html
import wx.gizmos as gizmos

import ab_ids
import ab_document

import ab_ids as ai
import ab_utils as ut


class PlxInfoDocFrame(ab_document.DocumentFrame):
    def __init__(self, parent, app, hanlder, plxname, *args, **kws):
        # set the doc as a private one
        ab_document.DocumentFrame.__init__(self, parent, app,
                                           hanlder, plxname)

        html_ctrl = wx.html.HtmlWindow(self)

        plx = app.readKey(ai.CfgParaPlxObject)
        o = plx.getElement(plxname).getInfo()
        des = (o.get('message') or '').strip()

        revision = '<h2>%s (%s) %s</h2>' % (ut.safestr(o.get('name')),
                                            ut.safestr(o.get('shortname')),
                                            ut.safestr(o.get('version')))
        if des[:6].lower() == '<html>':
            text = des.replace('<revision />', revision)
        else:
            # create the html content
            text = '<html><body>'
            text += revision
            # strip the lines
            lo = des.split('\n')
            while len(lo):
                li = lo.pop(0)
                # patch for the old text format
                if li.lower() == 'history':
                    lb = ''
                    while len(lo):
                        li = lo.pop(0)
                        if li == '':
                            break
                        if li[:4] != '----' and li[:4] != '====':
                            lb += '<li>%s</li>' % li
                    if len(lb):
                        text += '<h3>History</h3>'
                        text += '<ul>%s</ul><br>' % lb
                else:
                    text += '<br>' + li

            text += '</body></html>'

        sizer = wx.BoxSizer()

        html_ctrl.SetPage(text)
        sizer.Add(html_ctrl, 1, wx.EXPAND, 0)
        self.SetSizer(sizer)

        self.setReady()


class PlxInfoDocHandler(ab_document.DocumentHandler):
    def __init__(self):
        ab_document.DocumentHandler.__init__(self, 'plxinfo', PlxInfoDocFrame,
                                             True, False)


class PlxListDocFrame(ab_document.DocumentFrame):
    def __init__(self, parent, app, hanlder, *args, **kws):
        # set the doc as a private one
        ab_document.DocumentFrame.__init__(self, parent, app, hanlder,
                                           'Plug-in List')

        # output the string with following title
        plx = app.readKey(ai.CfgParaPlxObject)

        # Plug-in
        self.tree_ctrl = gizmos.TreeListCtrl(
            self, -1, style=wx.TR_DEFAULT_STYLE | wx.TR_FULL_ROW_HIGHLIGHT)
        self.tree_ctrl.AddColumn('Plug-in')
        self.tree_ctrl.AddColumn('Short')
        self.tree_ctrl.AddColumn('Version')
        self.tree_ctrl.AddColumn('Referral')
        self.tree_ctrl.AddColumn('File')
        self.tree_ctrl.SetColumnWidth(0, 175)
        self.tree_ctrl.SetColumnWidth(4, 200)

        num = 0
        ci = plx.getCategory()
        root = self.tree_ctrl.AddRoot('All')
        plxdir = self.app.readKey(ai.CfgParaPlxPath)
        if plxdir and plxdir[-1] != os.pathsep:
            plxdir += os.sep

        cats = ci.getCategories(all=True)
        cats.sort()
        for ca in cats:
            plx_list = plx.getPlxList(ca, required_all=True)
            if len(plx_list):
                num += len(plx_list)
                va = '%s (%d)' % (ci.getNameWithId(ca), len(plx_list))
                px = self.tree_ctrl.AppendItem(root, va)
                for plxname in plx_list:
                    o = plx.getElement(plxname).getInfo()
                    c = self.tree_ctrl.AppendItem(px, plxname)
                    self.tree_ctrl.SetItemText(
                        c, ut.safestr(o.get('shortname')), 1)
                    self.tree_ctrl.SetItemText(
                        c, ut.safestr(o.get('version')), 2)
                    self.tree_ctrl.SetItemText(
                        c, ut.safestr(','.join(o.get('referrals'))), 3)
                    filename = o.get('filename')
                    if filename and filename.find(plxdir) > -1:
                        filename = filename[len(plxdir):]
                    self.tree_ctrl.SetItemText(c, ut.safestr(filename), 4)

        self.tree_ctrl.SetItemText(root, 'All (%d)' % num)
        self.tree_ctrl.Expand(root)

        sizer = wx.BoxSizer()
        sizer.Add(self.tree_ctrl, 1, wx.EXPAND, 0)
        self.SetSizer(sizer)
        self.tree_ctrl.GetMainWindow().Bind(wx.EVT_RIGHT_DOWN, self.OnRightUp)
        self.setReady()

    def buildPopMenu(self):
        menu = wx.Menu()

        menu.Append(ab_ids.id_Expand, '&Expand')
        menu.Append(ab_ids.id_ExpandAll, 'Expand &All')
        menu.AppendSeparator()
        menu.Append(ab_ids.id_Collapse, '&Collapse')
        if self.tree_ctrl.GetChildrenCount(self.tree_ctrl.GetSelection()) == 0:
            menu.AppendSeparator()
            menu.Append(ab_ids.id_ShoHelpContent, 'Ab&out')

        return menu

    def OnRightUp(self, event):
        self.PopupMenu(self.buildPopMenu())

    def Update_Expand(self):
        return self.tree_ctrl.GetChildrenCount(self.tree_ctrl.GetSelection()) \
            > 0 and (not self.tree_ctrl.IsExpanded(
                     self.tree_ctrl.GetSelection()))

    def Cmd_Expand(self):
        self.tree_ctrl.Expand(self.tree_ctrl.GetSelection())

    def Update_ExpandAll(self):
        return True

    def Cmd_ExpandAll(self):
        self.tree_ctrl.ExpandAll(self.tree_ctrl.GetSelection())

    def Update_Collapse(self):
        return self.tree_ctrl.IsExpanded(self.tree_ctrl.GetSelection())

    def Cmd_Collapse(self):
        self.tree_ctrl.Collapse(self.tree_ctrl.GetSelection())

    def Cmd_PlxHelpContent(self):
        plx_name = self.tree_ctrl.GetItemText(self.tree_ctrl.GetSelection(), 0)
        self.app.openDocument('plxinfo', plx_name)


class PlxListDocHandler(ab_document.DocumentHandler):
    def __init__(self):
        ab_document.DocumentHandler.__init__(self, 'plxlist', PlxListDocFrame,
                                             True, False)
